<template>
  <el-page-header @back="router.go(-1)" title="返回">
    <template #content>
      <span>{{foodForm.id ? '编辑':'添加'}}单词</span>
    </template>
  </el-page-header>

  <div class="content">
    <el-form ref="foodFormRef" :model="foodForm" :rules="foodFormRule" :inline="false" label-width="160px">

      <el-form-item label="单词" prop="word">
        <el-input v-model="foodForm.word" placeholder="请输入单词" maxlength="20"/>
      </el-form-item>

      <el-form-item label="音标" prop="yinBiao">
        <el-input v-model="foodForm.yinBiao" placeholder="请输入音标" maxlength="20"/>
      </el-form-item>

      <el-form-item label="句子" prop="sentence">
        <el-input v-model="foodForm.sentence" placeholder="请输入音标" maxlength="20"/>
      </el-form-item>

      <el-form-item label="书籍" prop="bookId">
        <el-select style="width:200px" v-model="foodForm.bookId" placeholder="请选择书籍" @change="clearUnit">
          <el-option v-for="(item, index) in bookList" :key="index" :label="`${item.categoryName} - ${item.bookName}`"  :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="单元" prop="unitId">  
    <el-select style="width:200px" v-model="foodForm.unitId" placeholder="请选择单元">  
      <el-option v-for="(item, index) in filteredUnitList" :key="index" :label="`${item.bookName} - ${item.num}`" :value="item.id" />  
    </el-select> 
    <span>请选择书籍后再选择单元</span> 
  </el-form-item>  
      

      <el-form-item label="书籍图片:" prop="photo">

        <el-upload
            class="avatar-uploader"
            action="http://localhost:8081/file/upload"
            :headers="{token:token}"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="foodForm.photo" :src="foodForm.photo" style="width:178px;height:178px;" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="音频文件:" prop="voice">  
  <el-upload  
    class="audio-uploader"  
    action="http://localhost:8081/file/upload" 
    :headers="{token: token}"  
    :show-file-list="false"  
    :on-success="handleAudioSuccess"  
    :before-upload="beforeAudioUpload"  
    accept=".mp3,.wav"> <!-- 限制上传文件类型 -->  
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>  
    <div v-if="foodForm.voice" class="audio-preview">  
      <!-- 这里可以添加音频文件预览功能，如果需要的话 -->  
      <audio :key="audioKey" controls>  
  <source :src="audioSrc" type="audio/mpeg">  
  您的浏览器不支持 audio 元素。  
</audio>
      <span>已选择音频文件</span>  
    </div>  
  </el-upload>  
</el-form-item>

      <el-form-item label="翻译" prop="chinese">
        <el-input v-model="foodForm.chinese" type="textarea" />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleCancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref,computed,watch  } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { saveWord,findById } from "@/api/word";
import { getBookList } from "@/api/book"; 
import { getUnitList } from "@/api/unit"; 

import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();

let bookList = reactive([]);
let unitList = reactive([]);

const filteredUnitList = computed(() => {  
  if (!foodForm.bookId) return []; // 如果没有选择书籍，则不显示单元  
  return unitList.filter(unit => unit.bookId == foodForm.bookId); // 假设 unit 对象有 bookId 属性  
});  

const clearUnit = () => {
  foodForm.unitId = null;//当书籍被重新选择后，清空单元框内的数据
};


let foodFormRef = reactive(null);
let foodForm = reactive({
  id: null,
  word: null,
  bookId: null,
  unitId: null,
  photo: null,
  chinese: null,
  voice: null ,// 新增的音频文件属性
  yinBiao:null,
  sentence:null
});
let foodFormRule = reactive({

  word: [
    { required: true, trigger: 'blur',message: '请输入单词', }
  ],

  bookId: [
    { required: true, trigger: 'blur',message: '请选择书籍' }
  ],
 
  unitId: [
    { required: true, trigger: 'blur',message: '请选择单元' }
  ],
  photo: [
    { required: true, trigger: 'blur',message: '请提交图片' }
  ],
  chinese: [
    { required: true, trigger: 'blur',message: '请输入单词翻译' }
  ],
  voice: [  
  { required: true, trigger: 'blur' ,message: '请提交音频'}  
],
yinBiao: [  
  { required: true, trigger: 'blur' ,message: '请输入音标'}  
],
sentence: [  
  { required: true, trigger: 'blur' ,message: '请输入英语句子'}  
],
});

const token = sessionStorage.getItem("token");



// 加载版本信息
getBookList().then(resp => {
  bookList.push(...resp.data);
});

getUnitList().then(resp => {
  unitList.push(...resp.data);
});


  

if (route.query.wordId) {
  // 根据id查找
  findById(route.query.wordId).then(resp => {
    let word = resp.data;
    
    foodForm.id = word.id;
    foodForm.word = word.word;
    foodForm.bookId = word.bookId;
    foodForm.unitId = word.unitId;
    foodForm.photo = word.photo;
    foodForm.chinese = word.chinese;
    foodForm.voice = word.voice;
    foodForm.yinBiao = word.yinBiao;
    foodForm.sentence = word.sentence;

    
  }).catch(error => {
    // 错误处理
  });
}

// 图片上传相关方法
const handleAvatarSuccess = (resp, file) => {
  foodForm.photo = resp.data;
};

const beforeAvatarUpload = file => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

//音频上传相关方法
let audioKey = 0;

const handleAudioSuccess = (response, file) => {  
  // 假设服务器返回的是音频文件的URL  
  foodForm.voice = response.data;  // 更新表单中的音频文件信息  
  audioKey++; // 更新 key 以强制重新渲染 audio 元素 
  
};  
  
const audioSrc = computed(() => {  
  return foodForm.voice ? `${foodForm.voice}?v=${Date.now()}` : '';  
});

const beforeAudioUpload = file => {  
  const isAudio = file.type.startsWith('audio/');  
  const isLt10M = file.size / 1024 / 1024 < 10; // 限制文件大小，例如10MB  
  if (!isAudio) {  
    ElMessage.error('上传音频文件只能是音频格式!');  
  }  
  if (!isLt10M) {  
    ElMessage.error('上传音频文件大小不能超过 10MB!');  
  }  
  return isAudio && isLt10M;  
};

const handleSave = () => {
  // 判断是否校验通过
  if (foodFormRef && typeof foodFormRef.validate === 'function') {  
    foodFormRef.validate((valid) => {  
      if (valid) {  
        saveWord(foodForm.id, foodForm).then((resp) => {  
          if (resp.code === 200) { // 假设后端成功响应码为 200  
            router.push({ path: '/word/list' });  
            alert(resp.msg); // 显示成功消息 
            
          } else {  
            ElMessage.error(resp.msg);   
          }  
        }).catch(error => {  
          console.error('请求失败:', error);  
          alert('请求失败，请稍后再试');  
        });  
      }  
    });  
  }  
};
</script>



            
<style scoped>
.content {
  margin-top: 40px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>